package com.ccp.dev.qbdms.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.poi.excel.Excel;
import com.ccp.dev.core.util.AppUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.DateFormatUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.extend.model.ExtendSysFile;
import com.ccp.dev.extend.service.ExtendSysOrgService;
import com.ccp.dev.qbdms.annotation.AutoConfirmRequired;
import com.ccp.dev.qbdms.annotation.WaiXieRequired;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.dao.CommonalityDao;
import com.ccp.dev.qbdms.dao.WQbdCalRewandpunsDao;
import com.ccp.dev.qbdms.dao.WQbdFalProblemresetDao;
import com.ccp.dev.qbdms.dao.WQbdProblemProgressDao;
import com.ccp.dev.qbdms.dao.WQbdUnzeroWarningDao;
import com.ccp.dev.qbdms.model.WQbdCalRewandpuns;
import com.ccp.dev.qbdms.model.WQbdFalProblemreset;
import com.ccp.dev.qbdms.model.WQbdFalProblemvso;
import com.ccp.dev.qbdms.model.WQbdProblemProgress;
import com.ccp.dev.qbdms.model.WQbdQualityRewardsMessage;
import com.ccp.dev.qbdms.model.WQbdQualityRewardsMiddle;
import com.ccp.dev.qbdms.model.WQbdQualityRewardsMsgSub;
import com.ccp.dev.qbdms.model.WQbdUnzeroWarning;
import com.ccp.dev.qbdms.model.vo.SeriousFalProblemVo;
import com.ccp.dev.qbdms.model.vo.UnZeroProblemVo;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.ReadAttachmentUtil;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.model.SysFile;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.service.SysFileService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 质量问题管理 信息操作服务类
 *
 * @author sun
 * @date 2020-05-06 15:57:36
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WQbdFalProblemresetService extends BaseService<WQbdFalProblemreset> {

    @Resource
    private WQbdFalProblemresetDao dao;
    @Resource
    private WQbdCalRewandpunsDao wQbdCalRewandpunsDao;
    @Resource
    private WQbdFalProblemvsoService wQbdFalProblemvsoService;
    @Resource
    private ExtendSysOrgService extendSysOrgService;
    @Resource
    private SysFileService sysFileService;
    @Resource
    private WQbdQualityRewardsMessageService wQbdQualityRewardsMessageService;
    @Resource
    private WQbdQualityRewardsMiddleService wQbdQualityRewardsMiddleService;
    @Resource
    private WQbdUnzeroWarningDao wQbdUnzeroWarningDao;
    @Resource
    private WQbdQualityRewardsMsgSubService wQbdQualityRewardsMsgSubService;
    @Resource
    private WQbdProblemProgressDao wQbdProblemProgressDao;


    public HSSFWorkbook exportExcel(Excel excel, QueryFilter queryFilter) {
        List<WQbdFalProblemreset> dataList = this.dao.queryAll(queryFilter);
        int startRow = 1;
        //给每一个单元格赋值
        for (WQbdFalProblemreset data : dataList) {
            excel.cell(startRow, 0).value(data.getId());
            startRow++;
        }
        return excel.getWorkBook();
    }


    @Override
    public int add(WQbdFalProblemreset wQbdFalProblemreset) {
        addSubData(wQbdFalProblemreset);

        //新增历史数据
        WQbdFalProblemvso qbdFalProblemVso = new WQbdFalProblemvso();
        BeanUtils.copyNotNullProperties(qbdFalProblemVso, wQbdFalProblemreset);
        qbdFalProblemVso.setfCreateby(wQbdFalProblemreset.getfCreateby());
        qbdFalProblemVso.setfCreatetime(wQbdFalProblemreset.getfCreatetime());
        qbdFalProblemVso.setUpdateBy(null);
        qbdFalProblemVso.setUpdateTime(null);
        qbdFalProblemVso.setfVersiondate(wQbdFalProblemreset.getfCreatetime());
        qbdFalProblemVso.setfVersion(wQbdFalProblemvsoService.getMaxVersion(wQbdFalProblemreset.getId()) == null ? 1 : (wQbdFalProblemvsoService.getMaxVersion(wQbdFalProblemreset.getId()) + 1));
        wQbdFalProblemvsoService.add(qbdFalProblemVso);

        updateFileLevel(wQbdFalProblemreset.getfSkillcerfile());
        updateFileLevel(wQbdFalProblemreset.getfManagecerfile());

        WQbdQualityRewardsMessage wQbdQualityRewardsMessage = addQualityRewardsMsg(wQbdFalProblemreset);

        //做质量奖惩中间表数据的新增
        WQbdQualityRewardsMiddle wQbdQualityRewardsMiddle = new WQbdQualityRewardsMiddle();
        wQbdQualityRewardsMiddle.setId(ProjectUUIDUtils.getUUIDFor32());
        wQbdQualityRewardsMiddle.setDataid(wQbdFalProblemreset.getId());
        String genId = ProjectUUIDUtils.getUUIDFor32();
        wQbdQualityRewardsMiddle.setRewardsid(genId);
        wQbdQualityRewardsMiddleService.add(wQbdQualityRewardsMiddle);

        //质量奖惩信息数据的新增
        wQbdQualityRewardsMessage.setId(genId);
        wQbdQualityRewardsMessageService.add(wQbdQualityRewardsMessage);

        return super.add(wQbdFalProblemreset);
    }

    /**
     * 质量奖惩信息数据保存
     * @param wQbdFalProblemreset
     */
    private WQbdQualityRewardsMessage addQualityRewardsMsg(WQbdFalProblemreset wQbdFalProblemreset){
        //质量奖惩信息模块数据的新增
        WQbdQualityRewardsMessage wQbdQualityRewardsMessage = new WQbdQualityRewardsMessage();
        //事件名称
        wQbdQualityRewardsMessage.setIncidentName(wQbdFalProblemreset.getfProblemname());
        //密级
        wQbdQualityRewardsMessage.setSecret(wQbdFalProblemreset.getSecret());
        //是否完成责任追究
        wQbdQualityRewardsMessage.setCompleteAccountabilityFlag(wQbdFalProblemreset.getfConfirmdutyinvest());
        if(ZhiLiangConst.RESPONSIBILITY_INVESTIGATION.equals(wQbdFalProblemreset.getfDutyinvestigationtyp())){
            //类别
            wQbdQualityRewardsMessage.setQualityType(ZhiLiangConst.RESPONSIBILITY_INVESTIGATION);
        }else{
            wQbdQualityRewardsMessage.setQualityType(ZhiLiangConst.PUNISH);
        }
        //来源
        wQbdQualityRewardsMessage.setDataFrom(ZhiLiangConst.QUALITY_PROBLEM);
        //总金额
        if (StringUtil.isEmpty(wQbdFalProblemreset.getfAllcount())) {
            wQbdQualityRewardsMessage.setAggregateAmount(new BigDecimal(0));
        } else {
            wQbdQualityRewardsMessage.setAggregateAmount(wQbdFalProblemreset.getfAllcount());
        }
        //认定情况
        wQbdQualityRewardsMessage.setFirmlyBelieveSituation(wQbdFalProblemreset.getfIdentification());

        /**------------------公共字段-------------------------**/
        if(StringUtil.isNotEmpty(wQbdFalProblemreset.getTenantId())){
            wQbdQualityRewardsMessage.setTenantId(wQbdFalProblemreset.getTenantId());
        }
        if(StringUtil.isNotEmpty(wQbdFalProblemreset.getCreateBy())){
            wQbdQualityRewardsMessage.setCreateBy(wQbdFalProblemreset.getCreateBy());
        }
        if(BeanUtils.isNotEmpty(wQbdFalProblemreset.getCreateTime())){
            wQbdQualityRewardsMessage.setCreateTime(wQbdFalProblemreset.getCreateTime());
        }
        if(StringUtil.isNotEmpty(wQbdFalProblemreset.getFilldept())){
            wQbdQualityRewardsMessage.setFilldept(wQbdFalProblemreset.getFilldept());
        }
        if(StringUtil.isNotEmpty(wQbdFalProblemreset.getFilldeptid())){
            wQbdQualityRewardsMessage.setFilldeptid(wQbdFalProblemreset.getFilldeptid());
        }
        if(StringUtil.isNotEmpty(wQbdFalProblemreset.getFillman())){
            wQbdQualityRewardsMessage.setFillman(wQbdFalProblemreset.getFillman());
        }
        if(StringUtil.isNotEmpty(wQbdFalProblemreset.getFillmanaccount())){
            wQbdQualityRewardsMessage.setFillmanaccount(wQbdFalProblemreset.getFillmanaccount());
        }
        if(StringUtil.isNotEmpty(wQbdFalProblemreset.getFilldate())){
            wQbdQualityRewardsMessage.setFilldate(wQbdFalProblemreset.getFilldate());
        }
        if(StringUtil.isNotEmpty(wQbdFalProblemreset.getBelongdeptname())){
            wQbdQualityRewardsMessage.setBelongdeptname(wQbdFalProblemreset.getBelongdeptname());
        }

        /**------------------公共字段-------------------------**/

        //单位名称
        wQbdQualityRewardsMessage.setCreateTime(new Date());
        wQbdQualityRewardsMessage.setwQbdQualityRewardsMsgSubList(transformData(wQbdQualityRewardsMessage,wQbdFalProblemreset.getwQbdCalRewandpuns()));

        return wQbdQualityRewardsMessage;
    }

    /**
     * 子表数据转换
     * @param wQbdQualityRewardsMessage
     * @param wQbdCalRewandpunsList
     */
    private List<WQbdQualityRewardsMsgSub> transformData(WQbdQualityRewardsMessage wQbdQualityRewardsMessage,List<WQbdCalRewandpuns> wQbdCalRewandpunsList){
        List<WQbdQualityRewardsMsgSub> wQbdQualityRewardsMsgSubList = new ArrayList<>();
        if (BeanUtils.isNotEmpty(wQbdCalRewandpunsList)) {
            if (wQbdCalRewandpunsList.size() > 0) {
                for (WQbdCalRewandpuns wQbdCalRewandpun : wQbdCalRewandpunsList) {
                    WQbdQualityRewardsMsgSub wQbdQualityRewardsMsgSub = new WQbdQualityRewardsMsgSub();
                    wQbdQualityRewardsMsgSub.setId(ProjectUUIDUtils.getUUIDFor32());
                    wQbdQualityRewardsMsgSub.setRefid(wQbdQualityRewardsMessage.getId());
                    //单位名称
                    wQbdQualityRewardsMsgSub.setCompanyName(wQbdCalRewandpun.getfName());
                    //金额
                    wQbdQualityRewardsMsgSub.setMoney(new BigDecimal(wQbdCalRewandpun.getfMoney()));
                    //总人数
                    wQbdQualityRewardsMsgSub.setHeadcount(Long.parseLong(wQbdCalRewandpun.getfTotalnumber()));
                    //是否行政处分
                    wQbdQualityRewardsMsgSub.setDisciplinarySanctionFlag(wQbdCalRewandpun.getfIfpunishment());
                    //行政处分人数
                    wQbdQualityRewardsMsgSub.setDisciplinarySanctionCount(Long.parseLong(wQbdCalRewandpun.getfPunishmentnumber()));
                    //详细情况
                    wQbdQualityRewardsMsgSub.setDetailedInfomation(wQbdCalRewandpun.getfDetails());
                    wQbdQualityRewardsMsgSubList.add(wQbdQualityRewardsMsgSub);
                }
                return wQbdQualityRewardsMsgSubList;
            }
        }
        return null;
    }

    /**
     * 更改file密级名称
     * @param fileListStr
     */
    private void updateFileLevel(String fileListStr) {
        if (Objects.isNull(fileListStr) || "".equals(fileListStr)) {
            return;
        }

        JSONArray fileList = JSONArray.parseArray(fileListStr);
        for (Iterator iterator = fileList.iterator(); iterator.hasNext();) {
            JSONObject jsonObject = (JSONObject) iterator.next();
            String fileLevelText = jsonObject.getString("fileLevelText");
            String fileId = jsonObject.getString("fileId");
            Integer fileLevel = jsonObject.getInteger("fileLevel");
            SysFile sysFile = sysFileService.getOneById(fileId);
            sysFile.setFileLevel(fileLevel);
            sysFileService.update(sysFile);
        }
    }

    @Override
    public int update(WQbdFalProblemreset wQbdFalProblemreset) {
        wQbdCalRewandpunsDao.delByRefId(wQbdFalProblemreset.getId());
        addSubData(wQbdFalProblemreset);


        //新增历史数据
        WQbdFalProblemvso qbdFalProblemVso = new WQbdFalProblemvso();
        BeanUtils.copyNotNullProperties(qbdFalProblemVso, wQbdFalProblemreset);
        qbdFalProblemVso.setfCreateby(wQbdFalProblemreset.getfUpdateby());
        qbdFalProblemVso.setfCreatetime(wQbdFalProblemreset.getfUpdatetime());
        qbdFalProblemVso.setUpdateBy(null);
        qbdFalProblemVso.setUpdateTime(null);
        qbdFalProblemVso.setfVersiondate(wQbdFalProblemreset.getfUpdatetime());
        qbdFalProblemVso.setfVersion(wQbdFalProblemvsoService.getMaxVersion(wQbdFalProblemreset.getId()) == null ? 1 : (wQbdFalProblemvsoService.getMaxVersion(wQbdFalProblemreset.getId()) + 1));
        wQbdFalProblemvsoService.add(qbdFalProblemVso);

        updateFileLevel(wQbdFalProblemreset.getfManagecerfile());
        updateFileLevel(wQbdFalProblemreset.getfSkillcerfile());

        //更新
        WQbdQualityRewardsMessage wQbdQualityRewardsMessage = addQualityRewardsMsg(wQbdFalProblemreset);
        String rewardsId = wQbdQualityRewardsMiddleService.getRewardsIdByDataId(wQbdFalProblemreset.getId());
        wQbdQualityRewardsMessage.setId(rewardsId);
        wQbdQualityRewardsMessageService.update(wQbdQualityRewardsMessage);

        return super.update(wQbdFalProblemreset);
    }

    public int updategl(WQbdFalProblemreset wQbdFalProblemreset) {
        return super.update(wQbdFalProblemreset);
    }


    private void addSubData(WQbdFalProblemreset wQbdFalProblemreset) {
        if (BeanUtils.isNotEmpty(wQbdFalProblemreset.getwQbdCalRewandpuns())) {
            if (wQbdFalProblemreset.getwQbdCalRewandpuns().size() > 0) {
                List<WQbdCalRewandpuns> wQbdCalRewandpuns = wQbdFalProblemreset.getwQbdCalRewandpuns();
                for (WQbdCalRewandpuns wQbdCalRewandpun : wQbdCalRewandpuns) {
                    wQbdCalRewandpun.setId(ProjectUUIDUtils.getUUIDFor32());
                    wQbdCalRewandpun.setRefid(wQbdFalProblemreset.getId());
                }
                wQbdCalRewandpunsDao.addList(wQbdFalProblemreset.getwQbdCalRewandpuns());
            }
        }
    }

    @Override
    public int delByIdArray(String[] ids) {
        wQbdCalRewandpunsDao.delByRefIdArray(ids);
        wQbdFalProblemvsoService.delByIdArray(ids);
        return super.delByIdArray(ids);
    }

    /**
     * 1、判断是否可以归零：看上报状态是否是 集团的待确认
     * 2、归零：修改状态位+记录归零日期
     *
     * @param idArr
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NESTED)
    public void confirmZero(String[] idArr) throws Exception {
        List<WQbdFalProblemreset> wQbdFalProblemresetList = dao.getByIds(idArr);
        for (WQbdFalProblemreset wQbdFalProblemreset : wQbdFalProblemresetList) {
            if (autoConfirmZero(wQbdFalProblemreset)) {
                dao.update(wQbdFalProblemreset);
            }
            else{
                throw new Exception("不满足归零条件,归零失败");
            }
        }
    }

    /**
     * 自动确认功能，接受质量问题列表，当院级上报集团成功后，将上报的数据列表插过来进行自动归零确认
     *
     * @param wQbdFalProblemresetList
     * @return true表示可以归零 false表示不满足条件无法归零
     */
    public boolean autoConfirmZero(WQbdFalProblemreset wQbdFalProblemreset) throws IllegalAccessException {
        if ("否".equals(wQbdFalProblemreset.getfIfreset())) {
            return false;
        }
        //            当【归零方式】为不需归零时，不处理
        if ("不需归零".equals(wQbdFalProblemreset.getfResettype())) {
            return false;
        }
        //            当【归零方式】为技术归零时，【技术归零报告】不为空；
        if ("技术归零".equals(wQbdFalProblemreset.getfResettype()) && "".equals(wQbdFalProblemreset.getfSkillcerfile())) {
            return false;
        }
        //            当【归零方式】为管理归零时，【管理归零报告】不为空；
        if ("管理归零".equals(wQbdFalProblemreset.getfResettype()) && "".equals(wQbdFalProblemreset.getfManagecerfile())) {
            return false;
        }
        //            当【归零方式】为双归零时，【技术归零报告】和【管理归零报告】都不为空；
        if ("双归零".equals(wQbdFalProblemreset.getfResettype()) && "".equals(wQbdFalProblemreset.getfManagecerfile()) && "".equals(wQbdFalProblemreset.getfSkillcerfile())) {
            return false;
        }
        //            当满足前提条件时，问题发生名称，问题发生时间，是否确认归零，密级，
        //            型号代号，型号名称，型号研制阶段，型号类别，工作阶段，故障产品名称，
        //            故障产品所属的产品批次，生产分类，故障件阶段，产品级别，产品设计单位，
        //            产品生产单位，发生地点，是否靶场质量问题，是否批次性，是否三类问题，
        //            问题等级，硬件/软件，问题级别，归零周期，问题/故障现象描述，问题原因描述，
        //            纠正措施，管理因素分析，“四个两”要求对照分析，原因分类1，问题责任单位，
        //            归零方式，技术归零时间，管理归零时间，解决情况字段不为空。
        Field[] fields = wQbdFalProblemreset.getClass().getDeclaredFields();
        if (checkNullByAnnotation(wQbdFalProblemreset, fields, AutoConfirmRequired.class)) {
            return false;
        }

        //            当满足前提体检和条件1时，如果原因分类1为外协、外购时，外协外购乙方，是否集团配套，行业，外协性质不为空。
        if ("外协".equals(wQbdFalProblemreset.getfCausationclass1()) || "外购".equals(wQbdFalProblemreset.getfCausationclass1())) {
            if (checkNullByAnnotation(wQbdFalProblemreset, fields, WaiXieRequired.class)) {
                return false;
            }
        }

        //            如果原因分类1或原因分类2其中有一个为软件时，软件等级不为空。
        if ("软件".equals(wQbdFalProblemreset.getfCausationclass1()) || "软件".equals(wQbdFalProblemreset.getfCausationclass2())) {
            if (Objects.isNull(wQbdFalProblemreset.getfSoftrank())) {
                return false;
            }
        }

        wQbdFalProblemreset.setReportStatus(ZhiLiangConst.GROUP_CONFIRMED);
        wQbdFalProblemreset.setfIschange(DateFormatUtil.getNowByString(""));
        return true;
    }

    private boolean checkNullByAnnotation(Object obj, Field[] fields, Class clazz) throws IllegalAccessException {
        for (Field field : fields) {
            Annotation annotation = field.getAnnotation(clazz);
            if (Objects.nonNull(annotation)) {
                field.setAccessible(true);
                Object fieldValue = field.get(obj);
                if (Objects.isNull(fieldValue)) {
                    return true;
                }
            }
        }
        return false;
    }

    public List<WQbdFalProblemreset> getByIds(String[] lAryId) {
        return dao.getByIds(lAryId);
    }

    public void associations(HashMap<String, Object> map) {
        dao.associations(map);
    }

    /**
     * 查询上报流程的业务数据
     *
     * @param dataId
     * @param tableName
     * @return
     */
    public List<WQbdFalProblemreset> reportList(String dataId, String tableName) {
        return dao.reportList(dataId, tableName);
    }

    /**
     * 导入新增
     *
     * @param list 数据集
     * @throws Exception 异常
     */
    public void addImportData(List<WQbdFalProblemreset> list) throws Exception {
        List<WQbdCalRewandpuns> subData = new ArrayList<>();
        String path = BaseUtil.getCurrentTenOrgCodePath();
        Date date = new Date();
        String userId = ContextUtil.getCurrentUserId();
        String tenantId = ContextUtil.getCurrentUserTenantId();
        ZhiLiangConst.addCommonFields(list);

        List<WQbdQualityRewardsMiddle> wQbdQualityRewardsMiddleList = new ArrayList<>();
        List<WQbdQualityRewardsMessage> wQbdQualityRewardsMessageList = new ArrayList<>();

        list.forEach(a -> {
            String mainId = ProjectUUIDUtils.getUUIDFor32();
            a.setId(mainId);
            a.setfCreatetime(date);
            a.setfCreateby(userId);
            a.setTenantId(tenantId);
            a.setReportStatus(ZhiLiangConst.getDataInitStatusToHospital());
            if (StringUtil.isEmpty(a.getBelongdeptname())) {
                a.setBelongdeptname(path);
            }
            long beforeTime;
            if (StringUtils.isNotBlank(a.getfResettype()) && null != a.getfDetecttime()) {
                beforeTime = a.getfDetecttime().getTime();
                String resetType = a.getfResettype();
                if ("技术归零".equals(resetType) || "双归零".equals(resetType)) {
                    if (null != a.getfSkillresettime()) {
                        a.setfResetday(String.valueOf(
                            (a.getfSkillresettime().getTime() - beforeTime) / (1000 * 60 * 60
                                * 24)));
                    }
                } else if ("管理归零".equals(resetType)) {
                    if (null != a.getfManageresettime()) {
                        a.setfResetday(String.valueOf(
                            (a.getfManageresettime().getTime() - beforeTime) / (1000 * 60 * 60
                                * 24)));
                    }
                } else {
                    a.setfResetday("0");
                }
            }

            List<WQbdCalRewandpuns> wQbdCalRewandpuns = a.getwQbdCalRewandpuns();
            if (null != wQbdCalRewandpuns && wQbdCalRewandpuns.size() > 0) {
                wQbdCalRewandpuns.forEach(b -> {
                    b.setRefid(mainId);
                    b.setId(ProjectUUIDUtils.getUUIDFor32());
                    b.setCreateTime(date);
                    b.setCreateBy(userId);
                    b.setTenantId(tenantId);
                    if (StringUtils.isNotBlank(b.getfMoney())) {
                        b.setfMoney(b.getfMoney().replace(",", ""));
                    }
                    if (StringUtils.isNotBlank(b.getfTotalnumber())) {
                        b.setfTotalnumber(b.getfTotalnumber().replace(",", ""));
                    }
                    if (null == a.getfAllcount()) {
                        a.setfAllcount((new BigDecimal(b.getfMoney())));
                    } else {
                        a.setfAllcount(a.getfAllcount().add(new BigDecimal(b.getfMoney())));
                    }

                });
                subData.addAll(wQbdCalRewandpuns);
            }

            WQbdQualityRewardsMessage wQbdQualityRewardsMessage = addQualityRewardsMsg(a);
            //做质量奖惩中间表数据的新增
            WQbdQualityRewardsMiddle wQbdQualityRewardsMiddle = new WQbdQualityRewardsMiddle();
            wQbdQualityRewardsMiddle.setId(ProjectUUIDUtils.getUUIDFor32());
            wQbdQualityRewardsMiddle.setDataid(a.getId());
            String rewardsGenId = ProjectUUIDUtils.getUUIDFor32();
            wQbdQualityRewardsMiddle.setRewardsid(rewardsGenId);
            wQbdQualityRewardsMiddleList.add(wQbdQualityRewardsMiddle);

            //质量奖惩信息的新增
            wQbdQualityRewardsMessage.setId(rewardsGenId);
            wQbdQualityRewardsMessageList.add(wQbdQualityRewardsMessage);

            wQbdQualityRewardsMsgSubService.addAndUpdate(wQbdQualityRewardsMessage.getwQbdQualityRewardsMsgSubList(),rewardsGenId);
        });
        if (!list.isEmpty()) {
            dao.addList(list);
            wQbdQualityRewardsMessageService.addList(wQbdQualityRewardsMessageList);
            wQbdQualityRewardsMiddleService.addList(wQbdQualityRewardsMiddleList);
            if (!subData.isEmpty()) {
                wQbdCalRewandpunsDao.addList(subData);
            }
        }
    }


    public List<Dictionary> getOriginOrgToDicList() {
        List<SysOrg> sysOrgList = extendSysOrgService.getSubLevelOrg();
        sysOrgList = sysOrgList.stream().filter(sysOrg -> sysOrg.getIsTenant() == 1).collect(Collectors.toList());
        List<Dictionary> dicList = new ArrayList<>();
        for (SysOrg sysOrg : sysOrgList) {
            Dictionary dictionary = new Dictionary();
            dictionary.setItemName(sysOrg.getOrgName());
            dictionary.setItemValue(sysOrg.getCode());
            dicList.add(dictionary);
        }
        return dicList;
    }

    /**
     * 用于导出查询数据
     * @param queryFilter 参数
     * @return list
     */
    public List<WQbdFalProblemreset> queryAll(QueryFilter queryFilter){
       return dao.queryAll(queryFilter);
    }

    /**
     * webService上报方法
     * @param map 参数
     * @return ResultData
     * @throws Exception 抛出异常
     */
    public ResultData webReport(Map map) throws Exception{
        ObjectMapper objectMapper = new ObjectMapper();
        List<WQbdFalProblemreset> allList = objectMapper.readValue(map.get("list").toString(), new TypeReference<List<WQbdFalProblemreset>>(){});
        allList.forEach(a->{
            WQbdFalProblemreset wQbdFalProblemreset = getOneById(a.getId());
            if(BaseUtil.getCurrentSystemLevel() == BaseUtil.SystemLevel.GROUPLEVEL){
                a.setReportStatus(ZhiLiangConst.GROUP_TOBECONFIRMED);
            }else{
                a.setReportStatus(ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED);
            }
            if(BeanUtils.isEmpty(wQbdFalProblemreset)){
                add(a);
            }else{
                update(a);
            }
        });
        return ResultData.success("操作成功！");
    };

    /**
     * webService修改状态方法
     * @param map 参数
     * @return ResultData
     * @throws Exception 抛出异常
     */
    public ResultData webUpdateStatus(Map map) throws Exception{
        CommonalityDao commonalityDao = AppUtil.getBean(CommonalityDao.class);
        String tableName = map.get("tableName").toString();
        String dataId = map.get("dataId").toString();
        String status = map.get("status").toString();
        String[] businessIds = dataId.split(",");
        //这里暂时用的是无需上报的方法，因为该状态sql都相同所以随便调用了一个，日后有需求再修改
        commonalityDao.doNotNeedReportHospital(tableName,businessIds,status);
        return ResultData.success("更新状态成功！");
    }

    /**
     * 获取未归零数据
     * @param queryFilter
     * @return
     */
    public List<UnZeroProblemVo> getUnZeroList(QueryFilter queryFilter) {
        WQbdUnzeroWarning wQbdUnzeroWarning = wQbdUnzeroWarningDao.getOneByTenantId(ContextUtil.getCurrentUserTenantId());
        if (null == wQbdUnzeroWarning) {
            wQbdUnzeroWarning=wQbdUnzeroWarningDao.getDefault();
        }
        //获取未归零数据
        queryFilter.put("fIfreset","否");
        queryFilter.put("general",wQbdUnzeroWarning.getGeneral());
        queryFilter.put("serious",wQbdUnzeroWarning.getSerious());
        return dao.getUnZeroList(queryFilter);
    }

    /**
     * 获取严重质量问题列表
     * @param queryFilter
     * @return
     */
    public List<SeriousFalProblemVo> getSeriousList(QueryFilter queryFilter) {
        queryFilter.put("problemrank","serious");
        return dao.getSeriousList(queryFilter);
    }


    /**
     * 根据主表id查询主表加子表数据
     *
     * @param id 主表id
     * @return
     */
    public WQbdFalProblemreset getParentAndChilden(String id) {
        //zzy  增加子表数据
        List<WQbdCalRewandpuns> sonList = wQbdCalRewandpunsDao.getListByRefId(id);
        WQbdFalProblemreset parentData = dao.getParentAndChilden(id);
        parentData.setwQbdCalRewandpuns(sonList);
        return parentData;
    }

    /**
     * 保存接口传输的数据
     *
     * @param wQbdFalProblemreset 主表model,有子表的包含子表数据
     * @return
     */
    public void saveAll(List<WQbdFalProblemreset> dataList, List<ExtendSysFile> fileList) throws IllegalAccessException {
        // 保存附件文件
        ReadAttachmentUtil.getEntityData(dataList,fileList);

        for (WQbdFalProblemreset wQbdFalProblemreset : dataList) {
            // 如果上报数据中hospital为空,认为是三级上报来的,如果不为空,则认为是二级上报来的
            if (StringUtil.isEmpty(wQbdFalProblemreset.getFilldeptHospitalId())) {
                wQbdFalProblemreset.setBelongdeptname(BaseUtil.getCurrentTenOrgCodePath(wQbdFalProblemreset.getFilldeptid()));
            }
            else{
                wQbdFalProblemreset.setBelongdeptname(BaseUtil.getCurrentTenOrgCodePath(wQbdFalProblemreset.getFilldeptHospitalId()));
                // 接收方是集团级别时才触发自动归零,hospital不为空时表示接收方是集团级
                this.autoConfirmZero(wQbdFalProblemreset);
            }
            WQbdFalProblemreset temp = dao.getById(wQbdFalProblemreset.getId());
            if (temp != null) {
                update(wQbdFalProblemreset);
            } else {

                add(wQbdFalProblemreset);
            }
        }
    }

    public int saveProgress(WQbdProblemProgress wQbdProblemProgress) {
        return wQbdProblemProgressDao.insert(wQbdProblemProgress);
    }

    public List<WQbdProblemProgress> getAllProgress(String problemId) {
        return wQbdProblemProgressDao.getAll(problemId);
    }
}
